<?php

namespace App\Service;


use Google\Cloud\Translate\V2\TranslateClient;


class Translate
{

    // 谷歌翻译
    //   不能在国内服务器上使用
    //    https://cloud.google.com/php/docs/reference/cloud-translate/latest
    //    https://cloud.google.com/translate/docs/advanced/translate-text-advance?hl=zh_CN
    protected $client;


    // 字符串语言
    public function getLanguage($text)
    {
        $translate = $this->translateClient();
        $result    = $translate->detectLanguage($text);

        // 输出
        //echo $result['languageCode']."\n";

        return $result;
    }

    // 执行翻译
    public function translateTo($text, $language = 'en')
    {
        $language  = $this->getLanguageMime($language);
        $translate = $this->translateClient();
        $result    = $translate->translate($text, ['target' => $language,]);
        // 取消实体符号
        $result['text'] = html_entity_decode($result['text'] ?? '');
        $result['text'] = str_replace('&#39;',"'", $result['text']);

        /*try{
        } catch(\Exception $e){
            return $e->getMessage();
        }*/

        // 输出
        //echo $result['text']."\n";

        return $result;
    }


    #################################################################################################
    // 获取语言 类型
    protected function getLanguageMime($type = '')
    {
        $languages = ['en' => 'en', 'cn' => 'zh-CN', 'tc' => 'zh-TW',];
        if(empty($type)){
            return $languages;
        }

        return $languages[$type] ?? 'en';
    }

    // 实例化
    protected function translateClient()
    {
        // 谷歌翻译的 key
        if(empty($this->client)){
            $this->client = new TranslateClient(['key' => 'AIzaSyDB088_hCa5TvY_YcNpA0pC-U5qrJtVWj8']);

            // 这个要报错
            //$this->client = new TranslateClient(['key' => 'AIzaSyB78nl8YFJ7NmgZz9nmPj7bsriGjO5aoBI']);
        }

        return $this->client;
    }

}


